<template>
	<div class="dept-management">
		<!-- 顶部操作栏 -->
		<div class="operation-bar">
			<div class="left-section">
				<el-button type="primary" icon="el-icon-plus" @click="handleAdd" size="medium" class="add-btn">
					新增科室
				</el-button>
				<el-button type="success" icon="el-icon-refresh" @click="refreshData" :loading="loading" size="medium">
					刷新
				</el-button>
			</div>

			<div class="right-section">
				<el-input v-model="searchKeyword" placeholder="搜索科室名称/编码" prefix-icon="el-icon-search"
					style="width: 200px; margin-right: 10px;" size="medium" clearable @input="handleSearch" />

				<el-select v-model="filter.deptType" placeholder="科室类型" clearable
					style="width: 120px; margin-right: 10px;" size="medium" @change="handleFilter">
					<el-option label="全部类型" value=""></el-option>
					<el-option label="临床" value="临床"></el-option>
					<el-option label="医技" value="医技"></el-option>
					<el-option label="行政" value="行政"></el-option>
					<el-option label="后勤" value="后勤"></el-option>
				</el-select>

				<el-select v-model="filter.isActive" placeholder="状态" clearable style="width: 100px;" size="medium"
					@change="handleFilter">
					<el-option label="全部状态" value=""></el-option>
					<el-option label="启用" value="true"></el-option>
					<el-option label="停用" value="false"></el-option>
				</el-select>
			</div>
		</div>

		<!-- 科室表格 -->
		<div class="dept-table-container">
			<el-table :data="filteredDeptList" v-loading="loading" style="width: 100%" border stripe
				:default-sort="{prop: 'displayOrder', order: 'ascending'}" @sort-change="handleSortChange"
				class="dept-table">
				<el-table-column type="index" label="序号" width="70" align="center" fixed />

				<el-table-column prop="deptCode" label="科室编码" width="120" sortable align="center">
					<template slot-scope="{ row }">
						<span v-if="row.isEditing">
							<el-input v-model="row.editForm.deptCode" size="small" maxlength="20" :disabled="true"
								class="edit-input" />
						</span>
						<span v-else class="dept-code">
							<el-tag size="mini" type="info">{{ row.deptCode }}</el-tag>
						</span>
					</template>
				</el-table-column>

				<el-table-column prop="deptName" label="科室名称" min-width="180" sortable>
					<template slot-scope="{ row }">
						<div v-if="row.isEditing" class="edit-cell">
							<el-input v-model="row.editForm.deptName" size="small" placeholder="请输入科室名称"
								class="edit-input" />
						</div>
						<div v-else class="dept-info">
							<el-tag size="mini" :type="getDeptTypeTag(row.deptType)" class="dept-type-tag">
								{{ row.deptType }}
							</el-tag>
							<span class="dept-name">{{ row.deptName }}</span>
						</div>
					</template>
				</el-table-column>

				<el-table-column prop="deptType" label="科室类型" width="120" align="center">
					<template slot-scope="{ row }">
						<span v-if="row.isEditing">
							<el-select v-model="row.editForm.deptType" size="small" class="edit-select">
								<el-option label="临床" value="临床"></el-option>
								<el-option label="医技" value="医技"></el-option>
								<el-option label="行政" value="行政"></el-option>
								<el-option label="后勤" value="后勤"></el-option>
							</el-select>
						</span>
						<span v-else>
							<el-tag :type="getDeptTypeTag(row.deptType)" size="small" effect="plain">
								{{ row.deptType }}
							</el-tag>
						</span>
					</template>
				</el-table-column>

				<el-table-column prop="displayOrder" label="排序" width="100" sortable align="center">
					<template slot-scope="{ row }">
						<span v-if="row.isEditing">
							<el-input-number v-model="row.editForm.displayOrder" :min="1" :max="999" size="small"
								controls-position="right" class="edit-number" />
						</span>
						<span v-else class="order-badge">
							{{ row.displayOrder }}
						</span>
					</template>
				</el-table-column>

				<el-table-column prop="isActive" label="状态" width="100" align="center">
					<template slot-scope="{ row }">
						<span v-if="row.isEditing">
							<el-switch v-model="row.editForm.isActive" active-color="#13ce66"
								inactive-color="#ff4949" />
						</span>
						<span v-else>
							<el-tag :type="row.isActive ? 'success' : 'danger'" effect="dark" size="small"
								:class="{'status-tag': true, 'active': row.isActive}">
								{{ row.isActive ? '启用' : '停用' }}
							</el-tag>
						</span>
					</template>
				</el-table-column>

				<el-table-column label="操作" width="180" align="center" fixed="right">
					<template slot-scope="{ row }">
						<div class="action-buttons">
							<template v-if="row.isEditing">
								<el-button type="success" size="mini" icon="el-icon-check" @click="saveDept(row)"
									:loading="row.saving" class="save-btn">
									保存
								</el-button>
								<el-button type="info" size="mini" icon="el-icon-close" @click="cancelEdit(row)"
									:disabled="row.saving">
									取消
								</el-button>
							</template>
							<template v-else>
								<el-button type="primary" size="mini" icon="el-icon-edit" @click="startEdit(row)"
									:disabled="editingRow && editingRow !== row" class="edit-btn">
									编辑
								</el-button>
								<el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteDept(row)"
									class="delete-btn">
									删除
								</el-button>
							</template>
						</div>
					</template>
				</el-table-column>
			</el-table>

			<!-- 数据为空提示 -->
			<div v-if="!loading && filteredDeptList.length === 0" class="empty-tips">
				<el-empty description="暂无科室数据" v-if="searchKeyword || filter.deptType || filter.isActive !== ''">
					<el-button type="primary" @click="clearFilters">清除筛选条件</el-button>
				</el-empty>
				<el-empty description="暂无科室数据，点击新增按钮添加" v-else>
					<el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增科室</el-button>
				</el-empty>
			</div>
		</div>

		<!-- 统计数据 -->
		<div class="statistics" v-if="originalDeptList.length > 0">
			<el-row :gutter="20">
				<el-col :span="6">
					<el-card shadow="hover" class="stat-card">
						<div class="stat-item">
							<div class="stat-label">科室总数</div>
							<div class="stat-value">{{ originalDeptList.length }}</div>
						</div>
					</el-card>
				</el-col>
				<el-col :span="6">
					<el-card shadow="hover" class="stat-card">
						<div class="stat-item">
							<div class="stat-label">启用科室</div>
							<div class="stat-value">{{ enabledCount }}</div>
						</div>
					</el-card>
				</el-col>
				<el-col :span="6">
					<el-card shadow="hover" class="stat-card">
						<div class="stat-item">
							<div class="stat-label">停用科室</div>
							<div class="stat-value">{{ disabledCount }}</div>
						</div>
					</el-card>
				</el-col>
				<el-col :span="6">
					<el-card shadow="hover" class="stat-card">
						<div class="stat-item">
							<div class="stat-label">临床科室</div>
							<div class="stat-value">{{ clinicalCount }}</div>
						</div>
					</el-card>
				</el-col>
			</el-row>
		</div>

		<!-- 新增科室对话框 -->
		<el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @closed="handleDialogClosed"
			:close-on-click-modal="false">
			<el-form ref="deptForm" :model="formData" :rules="rules" label-width="80px">
				<el-form-item label="科室编码" prop="deptCode">
					<el-input v-model="formData.deptCode" placeholder="如：01、02等" maxlength="20" show-word-limit />
					<div class="form-tip">科室编码需唯一</div>
				</el-form-item>

				<el-form-item label="科室名称" prop="deptName">
					<el-input v-model="formData.deptName" placeholder="请输入科室名称" maxlength="50" show-word-limit />
				</el-form-item>

				<el-form-item label="科室类型" prop="deptType">
					<el-select v-model="formData.deptType" placeholder="请选择科室类型" style="width: 100%">
						<el-option label="临床科室" value="临床"></el-option>
						<el-option label="医技科室" value="医技"></el-option>
						<el-option label="行政科室" value="行政"></el-option>
						<el-option label="后勤科室" value="后勤"></el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="排序" prop="displayOrder">
					<el-input-number v-model="formData.displayOrder" :min="1" :max="999" controls-position="right"
						style="width: 100%" />
					<div class="form-tip">数字越小，显示越靠前</div>
				</el-form-item>

				<el-form-item label="状态" prop="isActive">
					<el-switch v-model="formData.isActive" active-text="启用" inactive-text="停用" active-color="#13ce66"
						inactive-color="#ff4949" />
				</el-form-item>

				<el-form-item label="备注" prop="remark">
					<el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="可选：科室描述或其他信息"
						maxlength="200" show-word-limit />
				</el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false" :disabled="submitting">
					取消
				</el-button>
				<el-button type="primary" @click="submitForm" :loading="submitting">
					确定
				</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import http from '../../utils/request.js'

	export default {
		name: 'DeptManagement',
		data() {
			// 验证科室编码
			const validateDeptCode = (rule, value, callback) => {
				if (!value) {
					callback(new Error('科室编码不能为空'))
					return
				}

				// 编码格式：字母数字组合
				const codePattern = /^[A-Za-z0-9]+$/
				if (!codePattern.test(value)) {
					callback(new Error('科室编码只能包含字母和数字'))
					return
				}

				// 检查编码是否重复（新增时检查）
				if (!this.isEditMode) {
					const exists = this.originalDeptList.some(dept => dept.deptCode === value)
					if (exists) {
						callback(new Error('该科室编码已存在'))
						return
					}
				}

				callback()
			}

			return {
				// 数据
				originalDeptList: [],
				loading: false,

				// 搜索和筛选
				searchKeyword: '',
				filter: {
					deptType: '',
					isActive: ''
				},

				// 编辑状态
				editingRow: null,
				isEditMode: false,

				// 对话框相关
				dialogVisible: false,
				submitting: false,
				dialogTitle: '新增科室',
				formData: {
					deptCode: '',
					deptName: '',
					deptType: '临床',
					isActive: true,
					displayOrder: 1,
					remark: ''
				},

				// 表单验证规则
				rules: {
					deptCode: [{
						required: true,
						validator: validateDeptCode,
						trigger: 'blur'
					}],
					deptName: [{
							required: true,
							message: '请输入科室名称',
							trigger: 'blur'
						},
						{
							min: 2,
							max: 50,
							message: '长度在 2 到 50 个字符',
							trigger: 'blur'
						}
					],
					deptType: [{
						required: true,
						message: '请选择科室类型',
						trigger: 'change'
					}],
					displayOrder: [{
						required: true,
						message: '请输入显示顺序',
						trigger: 'blur'
					}]
				}
			}
		},

		computed: {
			// 计算过滤后的科室列表
			filteredDeptList() {
				let list = this.originalDeptList

				// 关键词搜索
				if (this.searchKeyword) {
					const keyword = this.searchKeyword.toLowerCase()
					list = list.filter(item =>
						item.deptName.toLowerCase().includes(keyword) ||
						item.deptCode.toLowerCase().includes(keyword)
					)
				}

				// 类型筛选
				if (this.filter.deptType) {
					list = list.filter(item => item.deptType === this.filter.deptType)
				}

				// 状态筛选
				if (this.filter.isActive !== '') {
					const isActive = this.filter.isActive === 'true'
					list = list.filter(item => item.isActive === isActive)
				}

				return list
			},

			// 统计数据
			enabledCount() {
				return this.originalDeptList.filter(item => item.isActive).length
			},

			disabledCount() {
				return this.originalDeptList.filter(item => !item.isActive).length
			},

			clinicalCount() {
				return this.originalDeptList.filter(item => item.deptType === '临床').length
			}
		},

		async created() {
			await this.loadDeptData()
		},

		methods: {
			// 加载科室数据
			async loadDeptData() {
				this.loading = true
				try {
					const resp = await http.get('/admin/getDeptList')
					if (resp.data.code === 1) {
						this.originalDeptList = resp.data.data.map(item => ({
							...item,
							isEditing: false,
							saving: false,
							editForm: {
								...item
							}
						}))

						// 按显示顺序排序
						this.originalDeptList.sort((a, b) => a.displayOrder - b.displayOrder)
					} else {
						this.$message.error(resp.data.msg || '获取科室列表失败')
					}
				} catch (error) {
					this.$message.error('网络请求失败')
					console.error('加载科室数据失败:', error)
				} finally {
					this.loading = false
				}
			},

			// 刷新数据
			refreshData() {
				this.searchKeyword = ''
				this.filter.deptType = ''
				this.filter.isActive = ''
				this.loadDeptData()
			},

			// 搜索
			handleSearch() {
				// 实时搜索，无需额外处理
			},

			// 筛选
			handleFilter() {
				// 实时筛选，无需额外处理
			},

			// 清除筛选条件
			clearFilters() {
				this.searchKeyword = ''
				this.filter.deptType = ''
				this.filter.isActive = ''
			},

			// 排序改变
			handleSortChange({
				prop,
				order
			}) {
				this.originalDeptList.sort((a, b) => {
					let aValue = a[prop]
					let bValue = b[prop]

					if (typeof aValue === 'string') {
						aValue = aValue.toLowerCase()
						bValue = bValue.toLowerCase()
					}

					if (aValue < bValue) {
						return order === 'ascending' ? -1 : 1
					}
					if (aValue > bValue) {
						return order === 'ascending' ? 1 : -1
					}
					return 0
				})
			},

			// 开始编辑
			startEdit(row) {
				// 确保同一时间只有一个在编辑
				if (this.editingRow && this.editingRow !== row) {
					this.$message.warning('请先完成当前编辑')
					return
				}

				this.cancelEdit(this.editingRow)

				row.isEditing = true
				row.editForm = {
					...row
				}
				this.editingRow = row
			},

			// 保存编辑
			async saveDept(row) {
				try {
					// 验证必填字段
					if (!row.editForm.deptName || !row.editForm.deptName.trim()) {
						this.$message.error('科室名称不能为空')
						return
					}

					row.saving = true

					const response = await http.post('/admin/updateDept', {
						deptCode: row.deptCode,
						deptName: row.editForm.deptName,
						deptType: row.editForm.deptType,
						isActive: row.editForm.isActive,
						displayOrder: row.editForm.displayOrder,
						remark: row.editForm.remark || ''
					})

					if (response.data.code === 1) {
						this.$message.success('保存成功')

						// 更新本地数据
						Object.assign(row, row.editForm)
						row.isEditing = false
						row.saving = false
						this.editingRow = null

						// 重新排序
						this.originalDeptList.sort((a, b) => a.displayOrder - b.displayOrder)
					} else {
						this.$message.error(response.data.msg || '保存失败')
						row.saving = false
					}
				} catch (error) {
					this.$message.error('保存失败')
					row.saving = false
					console.error('保存科室信息失败:', error)
				}
			},

			// 取消编辑
			cancelEdit(row) {
				if (row) {
					row.isEditing = false
					row.saving = false
					row.editForm = {
						...row
					}
				}
				this.editingRow = null
			},

			// 删除科室
			deleteDept(row) {
				this.$confirm(`确定要删除科室【${row.deptName}】吗？`, '删除确认', {
					type: 'warning',
					confirmButtonText: '确定删除',
					cancelButtonText: '取消',
					confirmButtonClass: 'el-button--danger',
					center: true
				}).then(async () => {
					try {
						const response = await http.post('/admin/deleteDept', {
							deptCode: row.deptCode
						})

						if (response.data.code === 1) {
							this.$message.success('删除成功')

							// 从列表中移除
							const index = this.originalDeptList.findIndex(item => item.deptCode === row
								.deptCode)
							if (index !== -1) {
								this.originalDeptList.splice(index, 1)
							}
						} else {
							this.$message.error(response.data.msg || '删除失败')
						}
					} catch (error) {
						this.$message.error('删除失败')
						console.error('删除科室失败:', error)
					}
				}).catch(() => {
					// 用户取消删除
				})
			},

			// 新增科室
			handleAdd() {
				this.cancelEdit(this.editingRow)
				this.isEditMode = false
				this.dialogTitle = '新增科室'
				this.formData = {
					deptCode: '',
					deptName: '',
					deptType: '临床',
					isActive: true,
					displayOrder: this.getNextDisplayOrder(),
					remark: ''
				}
				this.dialogVisible = true
			},

			// 获取下一个显示顺序
			getNextDisplayOrder() {
				if (this.originalDeptList.length === 0) return 1

				const maxOrder = Math.max(...this.originalDeptList.map(item => item.displayOrder))
				return maxOrder + 1
			},

			// 提交表单（新增）
			submitForm() {
				this.$refs.deptForm.validate(async (valid) => {
					if (!valid) return

					this.submitting = true

					try {
						const response = await http.post('/admin/addDept', this.formData)

						if (response.data.code === 1) {
							this.$message.success('新增成功')
							this.dialogVisible = false
							await this.loadDeptData()
						} else {
							this.$message.error(response.data.msg || '新增失败')
						}
					} catch (error) {
						this.$message.error('新增失败')
						console.error('新增科室失败:', error)
					} finally {
						this.submitting = false
					}
				})
			},

			// 对话框关闭
			handleDialogClosed() {
				this.$refs.deptForm?.resetFields()
				this.submitting = false
			},

			// 获取科室类型标签样式
			getDeptTypeTag(type) {
				const typeMap = {
					'临床': 'success',
					'医技': 'primary',
					'行政': 'warning',
					'后勤': 'info'
				}
				return typeMap[type] || 'info'
			}
		}
	}
</script>

<style scoped>
	.dept-management {
		padding: 20px;
		background: #f0f2f5;
		min-height: calc(100vh - 60px);
	}

	.operation-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
		padding: 20px;
		background: white;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
	}

	.left-section {
		display: flex;
		gap: 10px;
	}

	.right-section {
		display: flex;
		align-items: center;
	}

	.add-btn {
		background: linear-gradient(135deg, #409EFF 0%, #337ecc 100%);
		border: none;
	}

	.dept-table-container {
		background: white;
		border-radius: 8px;
		padding: 20px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
		margin-bottom: 20px;
		min-height: 400px;
	}

	.dept-table {
		border-radius: 6px;
		overflow: hidden;
	}

	.dept-table :deep(.el-table__header-wrapper) {
		background: #fafafa;
	}

	.dept-table :deep(.el-table__body tr:hover) {
		background-color: #f5f7fa !important;
	}

	.dept-info {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.dept-type-tag {
		min-width: 40px;
		text-align: center;
	}

	.dept-name {
		font-weight: 500;
	}

	.dept-code {
		font-family: 'Consolas', monospace;
		font-weight: 600;
		color: #409EFF;
	}

	.order-badge {
		display: inline-block;
		width: 24px;
		height: 24px;
		line-height: 24px;
		border-radius: 50%;
		background: #409EFF;
		color: white;
		font-size: 12px;
		font-weight: bold;
		text-align: center;
	}

	.status-tag.active {
		animation: pulse 2s infinite;
	}

	@keyframes pulse {
		0% {
			opacity: 1;
		}

		50% {
			opacity: 0.7;
		}

		100% {
			opacity: 1;
		}
	}

	.action-buttons {
		display: flex;
		gap: 6px;
		justify-content: center;
	}

	.edit-input,
	.edit-select,
	.edit-number {
		width: 100%;
	}

	.empty-tips {
		padding: 40px 0;
		text-align: center;
	}

	.statistics {
		margin-top: 20px;
	}

	.stat-card {
		border-radius: 8px;
		transition: all 0.3s ease;
	}

	.stat-card:hover {
		transform: translateY(-5px);
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
	}

	.stat-item {
		text-align: center;
		padding: 10px;
	}

	.stat-label {
		font-size: 14px;
		color: #909399;
		margin-bottom: 8px;
	}

	.stat-value {
		font-size: 24px;
		font-weight: bold;
		color: #409EFF;
	}

	.form-tip {
		font-size: 12px;
		color: #909399;
		margin-top: 5px;
	}

	.dialog-footer {
		text-align: right;
		padding-top: 20px;
		border-top: 1px solid #ebeef5;
	}

	:deep(.el-table__row) {
		transition: all 0.3s ease;
	}

	:deep(.el-table__row.is-editing) {
		background-color: #f0f9ff !important;
	}

	:deep(.el-table__row.is-editing:hover) {
		background-color: #e6f7ff !important;
	}

	:deep(.el-table__row .el-input__inner) {
		border-radius: 4px;
	}

	:deep(.el-table__row .el-select .el-input__inner) {
		border-radius: 4px;
	}

	:deep(.el-switch) {
		height: 24px;
	}

	:deep(.el-switch__core) {
		height: 24px;
		border-radius: 12px;
	}

	:deep(.el-switch__core:after) {
		width: 20px;
		height: 20px;
	}
</style>